<template>
    <div class="app-container add">
        <CommonHeader :title="`销售出库单${title}`" :isShowBack="true"/>
        <div class="add-wrap">
            <div class="form-box">
                <div class="form-title">基本信息</div>
                <el-form :model="formData" ref="formData" :rules="rules" inline-message label-width="0" label-position="left">
                    <el-form-item prop="orderNo">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>出库单号</div>
                            <div class="select-wrap">
                                <van-field v-model="formData.orderNo" input-align="right" placeholder="输入出库单号" label=""/>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="relateType">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>关联单据类型</div>
                            <div class="select-wrap" @click="relateModalShow = true">
                                <span class="val" v-if="formData.relateType">{{ formData.relateTypeName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="relateOrders">
                        <div class="form-item">
                            <div class="label">
                                <span class="required"></span>单号选择<img src="@/assets/images/scan02.png" alt="" class="scan" @click.stop="handleScanCode">
                            </div>
                            <div class="select-wrap" @click="selectOrderEvent">
                                <span class="val" v-if="formData.relateOrders">{{ formData.relateOrders }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="planTime">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>计划出库日期</div>
                            <div class="select-wrap">
                                <span class="val" v-if="formData.planTime">{{ formData.planTime }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="applyPerson">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>申请人</div>
                            <div class="select-wrap">
                                <span class="val" v-if="formData.nickname">{{ formData.nickname }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 物料信息 -->
            <div class="material-box">
                <div class="item-title">物料信息</div>
                <div class="box-content">
                    <!-- <template v-if="saleOutInfoList.length > 0"> -->
                    <van-list v-if="saleOutInfoList.length > 0" v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false">
                        <van-cell v-for="item,index in saleOutInfoList" :key="index">
                            <materia-item :singleMaterial="item" :tabState="3" :index="index" :globalState="1" :isEdit="isCanEdit"></materia-item>
                        </van-cell>
                    </van-list>
                    <!-- </template> -->
                    <van-empty v-else description="暂无物料信息"></van-empty>
                </div>
            </div>
        </div>
        <div class="model-footer-wrap">
            <van-button type="info" class="save-btn" block round color="#548af1" size="normal" :loading="saveLoading" @click="completeEvent('save')" :disabled="!isCanEdit">保存</van-button>
            <van-button type="primary" class="complete-btn" block round color="#548af1" size="normal" :loading="completeLoading" @click="completeEvent('complete')" :disabled="!isCanEdit">提交完成</van-button>
        </div>
        <!-- 关联单据类型 -->
        <van-popup v-model="relateModalShow" position="bottom">
            <van-picker title="关联单据类型" show-toolbar :columns="relateList" value-key="label" @confirm="relateModalConfirm" @cancel="relateModalShow = false"/>
        </van-popup>
        <!-- 时间选择 -->
        <van-calendar v-model="dateShow" @confirm="calendarConfirm" color="#548AF1" />
        <!-- 申请人 -->
        <van-popup v-model="applyPersonShow" position="bottom">
            <van-picker title="申请人" show-toolbar :columns="applyPersonList" value-key="nickname" @confirm="applyPersonConfirm" @cancel="applyPersonShow = false"/>
        </van-popup>
        <!-- 扫码 -->
        <img src="@/assets/images/allocation/scan.png"  v-draggable  class="scan-img" @click="scanCodeEvent"/>
    </div>
</template>
<script>
import CommonHeader from "@/components/CommonHeader";
import { reqOrderNumberList, reqMaterialListByOrderNum, reqScanRecord } from "@/api/cj.js";
import { reqSaleOutReceiptDetail, reqWorkOrderReceiptsBom , reqCurrentPerson, reqUserList, reqWarehouseList, reqSaleOutReceiptsDetail, reqUpdateSaleOut,reqScanCodeRuleInfo,reqBatchSelect } from "@/api/cjSaleOutReceipt.js";
import MateriaItem from "./allocationDetail/components/MateriaItem.vue";
import { Toast, Dialog } from "vant";
import { formatDate } from "@/utils/toosls.js";
import { cloneDeep } from "lodash";
import { mapGetters,mapMutations,mapState,mapActions } from "vuex";
import { analysisScanCodeRules } from '@/utils/cjScanCodeRules.js'
export default {
  components: {
    CommonHeader,
    MateriaItem
  },
  data() {
    return {
        loading: false,
        finished: false,
        formData: {
            orderNo:"",
            relateTypeName: "销售订单",
            relateType: "salesOrder",
            relateOrders: "",
            planTime:formatDate(),
            nickname:"",
            applyPerson:"",
            personPhone:"",
            zhashu:""
        },
        rules: {
            orderNo:[{required:true,message:"请输入",trigger:"change"}],
            relateType:[{required:true,message:"请选择",trigger:"change"}],
            relateOrders:[{required:true,message:"请选择",trigger:"change"}],
            planTime:[{required:true,message:"请选择",trigger:"change"}],
            applyPerson:[{required:true,message:"请选择",trigger:"change"}],
            zhashu: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        orderNumberListShow:false,
        orderNumberList:[],
        relateModalShow: false,
        dateShow:false,
        applyPersonShow:false,
        applyPersonList:[],
        relateList:[{label:'销售订单',value:'salesOrder'}],
        materialLists:[],
        saleOutInfoList:[],
        warehouseList:[],
        pageData:{
            page:1,
            size:10,
            totalPages:0,
            totalElements:0
        },
        detailData: {},
        isCanEdit:true,
        completeLoading: false,
        saveLoading: false,
        detailMateriaShow: true,
    }
  },
  computed:{
    ...mapState(['cj_mh']),
    title(){
        const status = this.$route.query.status || 0;
        const t = status == 0 ? '编辑' : '详情';
        console.log('路由status参数:',status);
        return t;
    },
  },
  watch:{
    "formData.relateOrders":{
        handler(newValue,oldValue){
            if(newValue){
                if(this.detailMateriaShow) return
                this.getMaterialListByOrderNum();
                console.log('选则的单据编号',newValue);
            }
        },
    }
  },
  created() {
    // this.setMaterialContentHeight();
    // window.addEventListener('resize',this.setMaterialContentHeight);
    const saleOutNo = this.$route.query.saleOutNo;
    const saleOrderNumber = this.$route.params?.saleOrderNumber || '';
    this.getWareHouseInfo();
    this.getPurchaseDetail(saleOutNo, saleOrderNumber);
    this.getCurrentPerson();
    this.getUserList();
  },
  mounted(){
    this.setMaterialContentHeight();
    window.addEventListener('resize',this.setMaterialContentHeight);
    // const saleOutNo = this.$route.query.saleOutNo;
    // const saleOrderNumber = this.$route.params?.saleOrderNumber || '';
    // this.getWareHouseInfo();
    // this.getPurchaseDetail(saleOutNo, saleOrderNumber);
    // this.getCurrentPerson();
    // this.getUserList();
    // 扫码枪扫码
    const scanning_gun_enable = process.env.VUE_APP_BAR_CODE_SCANNING_GUN === 'true';
    if(scanning_gun_enable){
        window["ScanCodeMsg"] = (res) => {
        if (res) {
            console.log(res, "ScanCodeMsg这是首页");
            this.setScanResultFormat(res)
        }
        };
    }
  },
  beforeDestroy(){
    this.clearCjStore();
    console.log("编辑领料出库页面即将销毁...");
  },
  methods: {
    ...mapMutations('cj_mh',['SET_DEFAULT_ORDER_NUM','SET_RELATE_TYPE_INFO','SET_APPLY_PERSON']),
    ...mapActions('cj_mh',['clearCjStore', 'clearCjOrderNumber']),
    //获取销售出库单详情
    getPurchaseDetail(saleOutNo, saleOrderNumber){
        try{
            Toast.loading({message:'加载中...',duration: 0})
            reqSaleOutReceiptDetail(saleOutNo).then(response => {
                Toast.clear()
                if(response.code === 200){
                    const { orderNo, relateTypeName, refOrderNo, planTime, applyUserNickName, supplierName, ext, materialList, warehouseCode,warehouseId,warehouseName, warehouseManager, refType, status} = response.data;
                    this.formData.orderNo = orderNo;
                    this.formData.relateTypeName = relateTypeName || (this.relateList.find( rel => rel.value == refType).label ?? '');
                    this.formData.relateOrders = this.$store.state.cj_mh.relateOrders || refOrderNo;
                    this.formData.planTime = planTime;
                    this.formData.nickname = applyUserNickName;
                    this.formData.zhashu = ext.fieldOne;
                    this.detailData = response.data;
                    this.isCanEdit = status == 0 || status == 1;
                    if(saleOrderNumber && this.isCanEdit) {
                        this.getMaterialListByOrderNum();
                        console.log('重新选择的关联单据编号',saleOrderNumber);
                    } else {
                        const materialLists = materialList.map(v => {
                            const actualAmount = Number(v.extendMap.saleQuantity.planInQuantity || 0) - Number(v.extendMap.saleQuantity.hadInQuantity || 0) >= 0 ? Number(v.extendMap.saleQuantity.planInQuantity || 0) - Number(v.extendMap.saleQuantity.hadInQuantity || 0) : 0;
                            const warehouseArray = (this.warehouseList || []).map(house => {
                                if(v.extendMap.warehouse) {
                                    const materialHouse = v.extendMap?.warehouse?.find(materHouse => materHouse.warehouseCode === house.warehouseCode)
                                    return {
                                        ...house,
                                        inventoryAvailable: materialHouse?.inventoryAvailable || 0
                                    }
                                } else {
                                    return {...house,inventoryAvailable:0}
                                }
                            }).sort((a, b) => b.inventoryAvailable - a.inventoryAvailable) || [];
                            return {
                                checked:false,
                                materialEntity:{
                                    code:v.materialFields.code,
                                    name:v.materialFields.name,
                                    isBatchMag:v.materialFields.isBatchMag,
                                    standard:v.materialFields.standard,
                                    comp:v.materialFields.comp,
                                    unit:v.materialFields.unit,
                                    isDoubleUnit:v.materialFields.isDoubleUnit
                                },
                                planAmount: v.extendMap?.saleQuantity?.planInQuantity == 'null' ? 0 : v.extendMap?.saleQuantity?.planInQuantity,
                                actualAmount:actualAmount,
                                skuName:v.skuName,
                                realNum:v.actualNum,  //实际数量
                                materialRemark:v.remark,
                                supplierName:supplierName,
                                stockMaterialDetaiList: v.materialFields.isBatchMag ? (v.saleMaterialDetaiList || []).map( stock => {
                                    return {
                                        ...stock,
                                        barCode: stock.barCode || (stock?.stockInventoryDetailEntity?.barCode || ''),
                                        checked:false,
                                        isNoCanChange: true
                                    }
                                }) : [],  //批次列表
                                isExpand:true,
                                warehouseInfo:{
                                    warehouseName:warehouseName,
                                    warehouseId:warehouseId,
                                    warehouseCode:warehouseCode,
                                    warehouseManager:warehouseManager,
                                    warehouseList: warehouseArray
                                },
                                materialWarehouse: v.extendMap?.warehouse || [], // 物料对应仓库的数量
                                extendMap: v.extendMap,
                                lineNumber: v.rowIndex,
                                rowIndex: v.rowIndex
                            }
                        })
                        this.$nextTick(() => {
                            this.saleOutInfoList = materialLists;
                        })
                        if(this.isCanEdit) {
                            this.getMaterialListByOrderNum(true)
                        }
                    }
                }
                console.log("获取销售出库单详情",response);
            },error => {
                Dialog.confirm({title:'提示',message:'获取销售出库单详情失败，请重试',confirmButtonText:"确定",cancelButtonText:"取消"});
                console.log("获取销售出库单详情",error);
                Toast.clear()
            })
        } catch(err){
            console.log('获取销售出库单详情失败:',err);
            Toast.clear()
        }
    },
    //加载更多
    async onLoad(){
      console.log('滚动到底部===>',this.pageData);
    //   if(this.finished){
    //     return;
    //   }
    //   this.pageData.page += 1;
    //   this.getPurchaseList();
    },
    showOrderNumberListModal(){
        const relateType = this.formData.relateTypeName;
        if(!relateType){
            Toast({message:"请先选择关联单据类型",position:"top"});
            return;
        }
        this.orderNumberListShow = true;
    },
    //单号扫码选择
    async handleScanCode() {
        if(!this.formData.relateType) {
            Toast('请先选择关联单据类型')
            return;
        }
        window.flutter_inappwebview.callHandler("qrCode").then(response => {
            this.formData.relateOrders = response;
            //获取物料列表信息
            console.log("调用精致扫码api",response);
        },error => {
            Toast({message: error.message,position: 'top'});
            console.log('调用精致扫码api',error);
        });
    },
    relateModalConfirm(val){
        this.formData.relateTypeName = val.label;
        this.formData.relateType = val.value;
        this.relateModalShow = false;
        //获取单号列表信息
        this.getOrderNumberList();
    },
    orderNumberModalConfirm(val){
        this.formData.relateOrders = val.value;
        this.orderNumberListShow = false;
        //获取物料列表信息
    },
    //根据关联单据类型获取单号信息
    getOrderNumberList(){
        const relateType = this.formData.relateType;
        reqOrderNumberList(relateType).then(response => {
            if(response.code === 200 && response.data.content){
                const list = response.data.content;
                const array = list.map(k => {
                    return {
                        id:k.id,
                        purchaseCode:k.purchaseCode,
                        businessTypeName:k.businessTypeName,
                        createTime:k.createTime
                    }
                })
                const tmp = array.map(v => {
                    return {
                        label:v.purchaseCode + "--" + v.businessTypeName + "--" + v.createTime,
                        value:v.purchaseCode
                    }
                })
                this.orderNumberList = tmp;
                console.log(tmp);
            }
            console.log('获取单号列表api',response);
        },error => {
            console.log('获取单号列表api',error);
        })
    },
    //根据选择的单号信息获取对应的物料信息
    getMaterialListByOrderNum(type){
        const isCoverMaterialInfo = type === null ? false : true;
        const relateOrders = this.$store.state.cj_mh.relateOrders || this.formData.relateOrders;
        let parameter = {saleOrderNumber:relateOrders};
        if(!relateOrders){
            return;
        }
        let willExecuteFunction = reqSaleOutReceiptsDetail;
        willExecuteFunction(parameter).then(response => {
            console.log('销售订单/订单物料详情', response);
            if(response.code === 200 && response.data){
                this.formData.customerName = response.data.customerName
                this.formData.customerCode = response.data.customerCode
                const tmp = response.data?.saleOrderMaterials.map((item,index) => {
                    const actualAmount = Number(item.extendMap.saleQuantity.planInQuantity) - Number(item.extendMap.saleQuantity.hadInQuantity) >= 0 ? Number(item.extendMap.saleQuantity.planInQuantity) - Number(item.extendMap.saleQuantity.hadInQuantity) : 0;
                    const m = item.materialFields;
                    const warehouseArray = (this.warehouseList || []).map(house => {
                        if(item.extendMap.warehouse) {
                            const materialHouse = item.extendMap?.warehouse?.find(materHouse => materHouse.warehouseCode === house.warehouseCode)
                            return {
                                ...house,
                                inventoryAvailable: materialHouse?.inventoryAvailable || 0
                            }
                        } else {
                            return {...house,inventoryAvailable:0}
                        }
                    }).sort((a, b) => b.inventoryAvailable - a.inventoryAvailable) || [];
                    return {
                        checked:false,
                        materialEntity:{
                            code:m.code,
                            name:m.name,
                            isBatchMag:m.isBatchMag,
                            standard:m.standard,
                            comp:m.comp,
                            unit:m.unit,
                            isDoubleUnit:m.isDoubleUnit
                        },
                        planAmount: item.extendMap?.saleQuantity.planInQuantity,
                        actualAmount:actualAmount,
                        skuName: item.skuName,
                        realNum:item.actualAmount,  //实际数量
                        materialRemark:m.materialRemark || '',
                        supplierName:item.supplierName || '未知',
                        stockMaterialDetaiList:[],  //批次列表
                        isExpand:true,
                        warehouseInfo:{
                            warehouseName:warehouseArray[0]?.warehouseName || "",
                            warehouseId:warehouseArray[0]?.warehouseId || "",
                            warehouseCode:warehouseArray[0]?.warehouseCode || "",
                            warehouseManager:"",
                            warehouseList: warehouseArray
                        },
                        materialWarehouse: item.extendMap?.warehouse || [], // 物料对应仓库的数量
                        extendMap:{
                            zhashu:""
                        },
                        lineNumber: item.lineNumber
                    }
                })
                if(this.saleOutInfoList.length > 0 && isCoverMaterialInfo){
                    const materialCodeList = this.saleOutInfoList.map(v => v.materialEntity.code);
                    const filterMaterialList = tmp.filter(v => {
                        const code = v.materialEntity.code;
                        if(materialCodeList.includes(code)){
                            return false;
                        } else {
                            return true;
                        }
                    })
                    for(let i = 0; i < filterMaterialList.length; i ++){
                        const t = filterMaterialList[i];
                        this.saleOutInfoList.push(t);
                    }
                    console.log('合并后的物料信息',this.saleOutInfoList);
                } else {
                    this.saleOutInfoList = tmp;
                }
                if(tmp.length === 0){
                    Dialog.confirm({title: '提示',message: `单号${relateOrders}无相关物料信息`,confirmButtonText:"确定",cancelButtonText:"取消"});
                }
            }
        },error => {
            console.log('销售订单物料详情api',error);
        })
    },
    getDefaultPurchaseCode(){
        reqDefaultPurchaseCode().then(response => {
            if(response.code === 200 && response.data){
                this.formData.orderNo = response.data;
            }
            console.log('获取默认销售出库单号',response);
        },error => {
            console.log('获取默认销售出库单号',error);
        })
    },
    getCurrentPerson(){
        reqCurrentPerson().then(response => {
            if(response.code === 200 && response.data){
                const { id,nickname,mobile,username } = response.data;
                this.formData.nickname = nickname;
                this.formData.applyPerson = username;
                this.formData.personPhone = mobile;
            }
            console.log('获取当前用户信息',response);
        }, error => {
            console.log('获取当前用户信息',error);
        })
    },
    getUserList(){
        reqUserList().then(response => {
            if(response.code === 200 && response.data && response.data.content){
                const tmp = response.data.content.map(v => {
                    return {
                        id:v.id,
                        username:v.username,
                        nickname:v.nickname,
                        mobile:v.mobile
                    }
                })
                this.applyPersonList = tmp;
            }
            console.log('获取申请用户列表信息',response);
        }, error => {
            console.log('获取申请用户列表信息',error);
        })
    },
    calendarConfirm(date){
        console.log(date);
        const D = new Date(date);
        const y = D.getFullYear();
        const m = D.getMonth() + 1;
        const d = D.getDate();
        const h = D.getHours();
        const min = D.getMinutes();
        const s = D.getSeconds();
        const f = y + "-" + (m > 9 ? m : '0' + m) + "-" + (d > 9 ? d : '0' + d) + " 00:00:00";
        this.formData.planTime = f;
        this.dateShow = false;
    },
    applyPersonConfirm(person){
        const { id,username,nickname,mobile } = person;
        this.formData.nickname = nickname;
        this.formData.applyPerson = username;
        this.formData.personPhone = mobile;
        this.applyPersonShow = false;
    },
    provideCompanyPickerConfirm(company){
        const { code,name } = company;
        this.formData.provideCompany = name;
        this.formData.provideCompanyCode = code;
        this.provideCompanyShow = false;
    },
    setMaterialContentHeight(){
        const dom = document.querySelector(".box-content");
        const height = window.innerHeight;
        const offsetTop = dom.offsetTop;
        const offsetLeft = dom.offsetLeft;
        dom.style.height = height - offsetTop - 10 + 'px';
    },
    // 提交完成事件
    completeEvent(type){
        let validateResult = false;
        this.$refs.formData.validate(result => {
            validateResult = result;
        })
        if(!validateResult){
            Dialog.confirm({title: '提示',message: "请将基本信息填写完整",confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        //获取最新物料信息
        const materialList = cloneDeep(this.saleOutInfoList);
        //检查物料相关信息
        const list = cloneDeep(this.saleOutInfoList).filter(v => v.checked);
        if(list.length === 0){
            Dialog.confirm({title: '提示',message: "未选择任何物料信息",confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        let checkedResult = true;
        let messageTip = "";
        let warehouseMessage = "";
        let checkWarehouse = true;
        for(let i = 0; i < list.length; i ++){
            const t = list[i];
            const isBatchMag = t.materialEntity.isBatchMag;
            const materialCode = t.materialEntity.code;
            const materialName = t.materialEntity.name;
            if(isBatchMag){
                const a = t.warehouseInfo.warehouseId;
                const b = t.stockMaterialDetaiList.filter(v => v.checked && v.realNum && v.barCode);
                if(!a){
                    checkedResult = false;
                    messageTip = `物料${materialName}未填写仓库信息`;
                    break;
                }
                if(b.length === 0){
                    checkedResult = false;
                    messageTip = `物料${materialName}未填写批次实际出库数量/批号`;
                    break;
                }
            } else {
                const a = t.realNum;
                const b = t.warehouseInfo.warehouseId;
                if(!a){
                    checkedResult = false;
                    messageTip = `物料${materialName}未填写实际数量`;
                    break;
                }
                if(!b){
                    checkedResult = false;
                    messageTip = `物料${materialName}未填写仓库信息`;
                    break;
                }
            }
            // 校验仓库是否有数量
            console.log('仓库信息', t.warehouseInfo)
            if(t.warehouseInfo.warehouseId) {
                console.log('仓库信息', t.materialWarehouse, t.warehouseInfo.warehouseId)
                const materHouseItem = t.materialWarehouse.find(item => item.warehouseId == t.warehouseInfo.warehouseId)
                console.log(materHouseItem)
                if(!materHouseItem.inventoryAvailable) {
                    warehouseMessage += `物料${materialName}的仓库${materHouseItem.warehouseName}库存不足<br/>`
                    checkWarehouse = false
                }
            } else {
                // 如果没有仓库，必须要选择仓库
                warehouseMessage += `物料${materialName}未选择仓库<br/>`
                checkedResult = false
            }
        }
        if(!checkedResult){
            Dialog.confirm({title: '提示',message: messageTip,confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        if(!checkWarehouse) {
            warehouseMessage += '请重新选择仓库！'
            Dialog.confirm({title: '提示',message: warehouseMessage,confirmButtonText:"确定",cancelButtonText:"取消"})
            return
        }
        const filterMaterialList = materialList.filter(v => v.checked);
        for(let j = 0; j < filterMaterialList.length; j++){
            const t = filterMaterialList[j];
            const materialCode = t.materialEntity.code;
            const isBatchMag = t.materialEntity.isBatchMag;
            const realNum = t.realNum;
            const warehouseId = t.warehouseInfo.warehouseId;
            const batchList = t.stockMaterialDetaiList.filter(l => l.checked);
            t.stockMaterialDetaiList = batchList;
        }
        const tmp = filterMaterialList.map(v => {
            const isBatchMag = v.materialEntity.isBatchMag;
            let actualAmount = 0;
            const warehouseInfo = v.warehouseInfo.warehouseList.find(k => k.warehouseId == v.warehouseInfo.warehouseId);
            if(isBatchMag){
                actualAmount = v.stockMaterialDetaiList.reduce((pre,cur) => pre + Number(cur.realNum),0);
            } else {
                actualAmount = v.realNum;
            }
            return {
                actualAmount: actualAmount,
                actualNum: actualAmount,
                planAmount: actualAmount,
                planNum: actualAmount,
                code: v.materialEntity.code,
                productCode: v.materialEntity.code,
                warehouseId: warehouseInfo.warehouseId,
                warehouseCode: warehouseInfo.warehouseCode,
                warehouseName: warehouseInfo.warehouseName,
                warehouseUserName: this.formData.applyPerson,
                warehouseUserPhone: this.formData.personPhone,
                warehouseUserNickName: this.formData.nickname,
                remark: v.materialRemark,
                saleMaterialDetaiList:(v.stockMaterialDetaiList).map( stock => {
                    return {
                        ...stock,
                        code: v.materialEntity.code,
                        planAmount: stock.planNum,
                    }
                }),
                extendMap:v.extendMap,
                rowIndex: v.lineNumber || v.rowIndex,
            }
        })
        const { orderNo,relateTypeName,relateType,relateOrders,planTime,applyPerson,personPhone, nickname } = this.formData;
        const parameter = {
            id: this.detailData.id,
            inOrOutType: "salesIssueDoc",
            type: "salesIssueDoc",
            orderNo: orderNo,
            refType: relateType,
            refOrderNo: relateOrders,
            customerName: this.formData.customerName,
            customerCode: this.formData.customerCode,
            planTime: planTime,
            applyUserName: applyPerson,
            applyUserPhone: personPhone,
            applyUserNickName: nickname,
            materialList:tmp,
            relateType: relateType,
            relateOrders: relateOrders,
            createBy: applyPerson,
            applyPerson: applyPerson,
            personPhone: personPhone,
            status: type == 'save' ? this.detailData.status : 2
        }

        console.log('提交的数据--===', parameter)
        if(type == 'save'){
            this.saveLoading = true;
        }
        if(type == 'complete'){ // 保存并完成
            this.completeLoading = true;
        }
        reqUpdateSaleOut(parameter).then(response => {
            if(response.code === 200){
                Dialog.confirm({title: '提示', message: "出库成功", confirmButtonText:"确定",cancelButtonText:"关闭"}).then(confirm => {
                    //跳转首页
                    this.$router.push("/saleOutReceipt");
                },cancel => {
                    //跳转首页
                    this.$router.push("/saleOutReceipt");
                })
            }
            this.completeLoading = false
            this.saveLoading = false
            this.clearCjStore();
            this.clearCjOrderNumber();
            console.log('创建销售出库单api',response);
        },error => {
            this.completeLoading = false
            this.saveLoading = false
            const msg = error.response.data.message;
            Dialog.confirm({title: '提示',message: msg,confirmButtonText:"确定",cancelButtonText:"关闭"});

            console.log('创建销售出库单api',error);
        })
    },
    //查询仓库信息
    getWareHouseInfo(){
      reqWarehouseList().then(response => {
        if(response.code === 200){
          this.warehouseList = response.data.map(e => {
            return {
              warehouseCode:e.warehouseCode,
              warehouseName:e.warehouseName,
              warehouseId:e.warehouseId,
              warehouseType:e.warehouseType
            }
          })
        }
        console.log('请求仓库列表信息',response);
      },error => {
        console.log('请求仓库列表信息',error);
      })
    },
    selectOrderEvent(){
        if(!this.isCanEdit) return
        const relateType = this.formData.relateType;
        console
        if(!relateType){
            Dialog.confirm({title: '提示',message: '请选择关联类型',confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        this.detailMateriaShow = false
        this.$router.push({path:"/saleOutReceipt/salesOrder",query:{type:relateType, saleOutNo: this.$route.query.saleOutNo}});
    },
    async scanCodeEvent(){
        if(this.saleOutInfoList && !this.saleOutInfoList.length) {
            Dialog.confirm({title: '提示',message: '请先选择工单/当前单号无相关物料',confirmButtonText:"确定",cancelButtonText:"取消"});
            return
        }
        const isDevelopment = process.env.NODE_ENV === 'development';
        let scanCode = '950080005/CKPC20250527001/2';
        try {
            if(!isDevelopment){
                scanCode = await window.flutter_inappwebview.callHandler('qrCode');
            }
            console.log('调用精致提供的扫码api',scanCode);
        } catch (error) {
            Dialog.confirm({title: '提示',message: '扫码异常，尝试重新打开本程序',confirmButtonText:"确定",cancelButtonText:"取消"});
            console.log("调用精致提供的扫码api",error);
            return;
        }
        this.setScanResultFormat(scanCode)
    },
    // 对扫码后的结果进行处理
    async setScanResultFormat(scanCode) { 
        let decodeFun = null;
        try {
            decodeFun = await this.getScanCodeRuleInfo();
        } catch (error) {
            decodeFun = analysisScanCodeRules;
            console.log('请求解码规则脚本失败,即将调用本地解码函数...');
        }
        const { materialInfo, batchInfo, numInfo } = decodeFun(scanCode);
        const materialList =  this.saleOutInfoList // cloneDeep(this.workOrderInfoList);
        console.log('当前物料信息====>',materialList);
        const filterMaterialList = materialList.filter(v => materialInfo == v.materialEntity.code);
        if(filterMaterialList.length === 0){
            Dialog.confirm({title: '提示',message: `该单号未包含此物料${materialInfo},请检查`,confirmButtonText:"确定",cancelButtonText:"取消"});
            return;
        }
        filterMaterialList[0].checked = true;
        //物料是否批次
        if(filterMaterialList[0].materialEntity.isBatchMag){
            
            const obj = {checked:true,barCode:batchInfo,planNum:filterMaterialList[0].planAmount,realNum:numInfo};
            if(!batchInfo){
                // 没有批次号则不允许添加
                Dialog.confirm({title: '提示',message: `该物料${materialInfo},没有该批次号${batchInfo}请检查`,confirmButtonText:"确定",cancelButtonText:"取消"});
                return
            }
            // 查询是否有该批次
            let warehouseCode = filterMaterialList[0]?.warehouseInfo.warehouseCode
            const res = await reqBatchSelect({materialCode: materialInfo, barCode: batchInfo, warehouseCode})
            if(res.code == 200) {
                if(!res.data) {
                    Dialog.confirm({title: '提示',message: `该物料${materialInfo},没有该批次号${batchInfo}请检查`,confirmButtonText:"确定",cancelButtonText:"取消"});
                    return
                }
                if(filterMaterialList[0].stockMaterialDetaiList.findIndex(v => v.barCode == batchInfo) === -1){
                    filterMaterialList[0].stockMaterialDetaiList.push(obj);
                } else {
                    const y = filterMaterialList[0].stockMaterialDetaiList.find(v => v.barCode == batchInfo);
                    y.checked = true;
                    y.planNum = filterMaterialList[0].planAmount;
                    y.realNum = numInfo;
                }
            }
            return;
        } else {
            filterMaterialList[0].realNum = numInfo;
            console.log('当前物料信息====>',filterMaterialList[0]);
            return;
        }
    },
    //获取解码规则脚本
    getScanCodeRuleInfo(){
        return new Promise((resolve,reject) => {
            reqScanCodeRuleInfo().then(response => {
                if(response.code == 200 && response.data){
                    const functionStr = response.data.value;
                    const fun = new Function('return ' + functionStr);
                    resolve(fun());
                }
                console.log('获取解码规则脚本api',response);
            },error => {
                console.log('获取解码规则脚本api',error);
                reject(new Error("请求解码规则脚本失败"));
            })
        })
    },
  }
  
}
</script>

<style lang="scss" >
.scan-img{
  position: fixed;
  bottom: 8vh;
  right: 0;
  // transform: translateX(-50%);
  width: 82px;
  height: 82px;
  z-index: 2;
}
.add-wrap{
    .el-form-item__error{
        position: absolute !important;
        top: 25px;
        right: 30px;
    }
    .el-textarea__inner{
        border: none !important;
        text-align: right !important;
    }
}
</style>
<style lang="scss" scoped>
.header-top{
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 2;
}
.add-wrap{
    padding-top: 64px;
    padding-bottom: 80px;
    .form-box{
        margin: 12px 12px 0;
        background-color: #ffffff;
        border-radius: 4px;
        .el-form-item{
            margin-bottom: 0 !important;

        }
        .form-title{
            font-size: 16px;
            margin: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            border-bottom: 1px #F3F3F3 solid;
            position: relative;
            padding-left: 8px;
            &::before{
                content: '';
                width: 4px;
                height: 14px;
                background-color: #548AF1;
                position: absolute;
                left: 0;
                top: 13px;
            }
        }
        .form-item{
            margin: 0 7px;
            padding: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px #F3F3F3 dotted;
            font-size: 13px;
            color: #333333;
            .label{
                display: flex;
                align-items: center;
                .required{
                    content: '';
                    color: #FF0000;
                    display: inline-block;
                    width: 6px;
                    height: 6px;
                    background: url('../../assets/images/required.png') no-repeat;
                    background-size: 100% 100%;
                    margin-right: 4px;
                }
                .scan{
                    width: 19px;
                    height: 19px;
                    margin-left: 9px;
                }
            }
            .info-wrap{
                text-align: right;
                .code{
                    color: #548AF1;

                }
            }
            input{
                width: 100%;
                border: none;
                text-align: right;
            }
            .select-wrap{
                color: #999999;
                .val{
                    color: #333333;
                }
                i{
                    margin-left: 5px;
                    color: #909090;
                }
            }
        }
        .remark-wrap{
            padding: 6px 0;
            .textarea{
                // height: 35px;
                width: 100%;
                border: none;
                font-size: 14px;
                color: #333333;

            }
        }
    }
    .material-box{
        margin: 12px 12px 0;
        background-color: #ffffff;
        border-radius: 4px;
        .item-title{
            font-size: 16px;
            margin: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            border-bottom: 1px #F3F3F3 solid;
            position: relative;
            padding-left: 8px;
            &::before{
                content: '';
                width: 4px;
                height: 14px;
                background-color: #548AF1;
                position: absolute;
                left: 0;
                top: 13px;
            }
        }
        .box-content{
            width: 100%;
            height: 350px;
            overflow: auto;
            .cell-desc-title{
                font-size:14px;
                font-weight: normal;
            }
            .cell-desc-scan{
                width: 19px;
                height: 19px;
            }
        }
    }
}
.model-footer-wrap{
    width: 100%;
    display: flex;
    .save-btn{
        flex:1;
        margin-right: 10px;
    }
    .complete-btn{
        flex:3;
    }
}
.van-action-sheet .content{
    width: 100%;
    height: 250px;
    padding:16px 16px 160px;
    overflow: auto;
    .content-item{
        width:100%;
        height: 50px;
        margin-bottom: 10px;
        display: flex;
        flex-wrap: wrap;
        .item-span1{
            font-size: 12px;
            padding: 0px 15px;
        }
        .item-span2{
            font-size: 12px;
            padding: 0px 15px;
        }
        .item-span3{
            font-size:12px;
            padding: 0px 15px;
        }
    }
}
</style>
